package wdevent

import (
	"sync"
)

type event struct {
	lock      sync.RWMutex
	eventlist map[string][]EventCall
	eventlock map[string]*sync.Mutex
}

func NewEvent() I_Event {
	return &event{
		eventlist: make(map[string][]EventCall),
		eventlock: make(map[string]*sync.Mutex),
	}
}

//AddEvent ..添加事件
func (e *event) AddEvent(key string, call EventCall) {
	e.lock.Lock()
	if _, ok := e.eventlist[key]; ok {
		e.eventlist[key] = append(e.eventlist[key], call)
	} else {
		e.eventlist[key] = make([]EventCall, 0)
		e.eventlist[key] = append(e.eventlist[key], call)
		e.eventlock[key] = &sync.Mutex{}
	}
	e.lock.Unlock()
}
func (e *event) RemoveEvent(key string) {
	e.lock.Lock()
	if _, ok := e.eventlist[key]; ok {
		delete(e.eventlist, key)
		delete(e.eventlock, key)
	}
	e.lock.Unlock()
}
func (e *event) ExecEvent(key string, offset interface{}) {
	e.lock.RLock()
	if _, ok := e.eventlist[key]; ok {
		e.eventlock[key].Lock()
		for _, v := range e.eventlist[key] {
			v(offset)
		}
		e.eventlock[key].Unlock()
	}
	e.lock.RUnlock()
}
func (e *event) Clear() {
	e.lock.Lock()
	for k, _ := range e.eventlist {
		delete(e.eventlist, k)
		delete(e.eventlock, k)
	}
	e.lock.Unlock()
}
